package gyb.rasa.common.handler.handler;

import gyb.rasa.common.handler.exceptionhandler.MyException;
import gyb.rasa.common.utils.ApplicationContextProvider;
import gyb.rasa.common.utils.IPUtils;
import gyb.rasa.entity.Ip;
import gyb.rasa.service.IpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: 郜宇博
 */
@Component
public class IPInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取上下文工具，因为无法使用autowire
        ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
        //获取ipservice
        IpService ipService = applicationContext.getBean(IpService.class);
        String currentIp = IPUtils.getIpAddr(request);
        //获取所有ip
        List<Ip> list = ipService.list();
        for (Ip ip : list) {
            //表中有符合的ip,并且被禁
            if (ip.getIp().equals(currentIp) && ip.getStatus() == 0){
                throw new MyException(20001,"该ip被禁用");
            }
        }
        return true;

    }
}
